package ar.com.mobile.persistence.container;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import java.util.Properties;

public class Property implements Observer {
	/**
	 * Ruta del archivo de propiedades
	 */
	private String path = null;
	/**
	 * Propiedades que vamos a utilizar en la aplicacion
	 */
	private Properties properties = new Properties();
	/**
	 * Thread que revisa (en un cierto intervalo de tiempo) si el archivo de properties cambia
	 */
	private PropertyService thread = null;
	
	/**
	 * 
	 * @param path
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public Property (String path, boolean verificar) throws FileNotFoundException, IOException{
		if (path == null || path.isEmpty())
			new IllegalArgumentException("La ruta del archivo esta vacia");
		
		this.path = path;		
		File f = new File(path);
		
		this.properties.load(new FileInputStream(f));
		
		if (verificar){
			this.thread = new PropertyService(f.lastModified(), path);	
			this.thread.addObserver(this);
		}
	}
	
	/**
	 * 
	 * @param path
	 * @param verificar
	 * @param initialDelay
	 * @param delay
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public Property (String path, boolean verificar, long initialDelay, long delay) throws FileNotFoundException, IOException{
		if (path == null || path.isEmpty())
			new IllegalArgumentException("La ruta del archivo esta vacia");
		
		this.path = path;		
		File f = new File(path);
		
		this.properties.load(new FileInputStream(f));
		
		if (verificar){
			this.thread = new PropertyService(f.lastModified(), path, initialDelay, delay);	
			this.thread.addObserver(this);
		}
	}
	
	@Override
	public void update(Observable o, Object arg) {		
		try {
			this.properties.load(new FileInputStream(this.path));			
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}
